#include <iostream>
#include <curl/curl.h>
using namespace std;

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp);
string curl_get(const char* url, string data);

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
    // size_t realsize=size * nmemb;
    // std::string * str=static_cast<std::string*>(userp);
    // str->append(static_cast<char*>(contents),realsize);
    // return realsize;
}

string curl_get(const char* url, string data)
{
    CURL *curl;
    CURLcode res;
    std::string readBuffer;
    // 初始化模块
    curl_global_init(CURL_GLOBAL_DEFAULT);
    // 初始化请求库
    curl = curl_easy_init();
    if(curl)
    {
        // CURLOPT_URL 请求的网站
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // CURLOPT_WRITEFUNCTION 设置回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        curl_easy_setopt(curl, CURLOPT_POST,1L);
        // curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
        // curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE,data.length());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
        // 执行CURL访问网站
        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        } else {
            // std::cout << readBuffer << std::endl;
        }
 
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    
    return readBuffer;
}

// op=4&sql=select * from log
int main(int argc, char const *argv[])
{
    string data="op=4&sql=select * from log";
    const char* url="http://127.0.0.1/api/index.php";
// http://127.0.0.1/api/index.php?op=4&sql=select%20*%20from%20log
    string res;
    res=curl_get(url,data);
    cout << res << endl;
    return 0;
}